package bTree.LeetCode;

import javax.swing.tree.TreeNode;
import java.util.*;

public class 二叉树的层平均值 {
    List<Double>res=new ArrayList<>();
    public List<Double> averageOfLevels(TreeNode root) {
        bfs(root);
        return res;
    }

    private void bfs(TreeNode root) {
        Queue<TreeNode>queue=new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()){
            int len=queue.size();
            long sum=0;
            for (int i=0;i<len;i++){
                if (queue.peek().left!=null){
                    queue.add(queue.peek().left);
                }
                if (queue.peek().right!=null){
                    queue.add(queue.peek().right);
                }
                sum+=queue.poll().val;
            }
            Double avg=sum*1.0/len;
            res.add(avg);
        }
    }
}